home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part2 / 11744 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.9 KB

  1. Path: hillres151.cc.purdue.edu!pacman
  2. From: pacman@hillres151.cc.purdue.edu (PacMan)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: pointers and functions
  5. Date: 26 Mar 1996 11:01:48 GMT
  6. Organization: prohibited
  7. Message-ID: <4j8iqs$9n9@mozo.cc.purdue.edu>
  8. References: <4j6dol$58g@news.bu.edu>
  9. NNTP-Posting-Host: hillres151.cc.purdue.edu
  10.  
  11. In article <4j6dol$58g@news.bu.edu>, wai yip <lachesis@bu.edu> wrote:
  12. >can someone help me find the bug in this program?
  13.  
  14. I found one. I'm not saying I found all of them..
  15. >this is the file the program reads from:
  16.  
  17. [which we didn't need so I snipped]
  18.  
  19. >
  20. >and here is the part of the program:
  21. >
  22.  
  23. [snip some..]
  24. >
  25. >mazeType *readMaze(char *fname);
  26. >int printMaze(mazeType *maze);
  27. >
  28. >
  29. >mazeType *readMaze(char *fname)
  30. >{
  31. >FILE *ifp;
  32. >char c,*Array=NULL;
  33. >int x=0;
  34. >mazeType Maze;
  35.  ^^^^^^^^^^^^^^
  36. >mazeType *StructPtr=NULL;
  37.  
  38. [snip some stuff that puts data into the Maze struct]
  39.  
  40. >StructPtr=&Maze;
  41. >return (StructPtr);
  42. >}
  43.  
  44. The problem is that Maze is a local variable. It only exists inside the
  45. function readMaze. When you return its address, readMaze is finished, and its
  46. local variables disappear, and the calling function is left with a pointer to
  47. some data that isn't there anymore. After that, anything can happen-- bus
  48. errors, segmentation faults, the end of the universe...
  49.  
  50. What you can do to correct this is to have the calling function pass in the
  51. address of an already allocated mazeType, and fill it in, or make the
  52. variable Maze be external or static so that it will outlive the function
  53. call, or have it point to malloc'ed space. I can't decide which solution is
  54. best for you without studying your program in detail, and I'm not feeling
  55. up to doing that.
  56. -- 
  57. Alan Curry
  58. -----BEGIN GEEK CODE BLOCK-----
  59. Version: 3.1
  60. GCS d? s++:-- a--- C+++ UL++++ P+ L+++>++++ E--- W-- N++ o K? w--- O? M--
  61. V?  PS+ PE+ Y+ PGP- t* 5++ X+++ R- tv++ b- DI- D++ G+++ !e h! r-->+++ y?
  62. ------END GEEK CODE BLOCK------
  63.